local BaseData = require("data.base.BaseData")
local ResourceData = class("ResourceData", BaseData)
local ResourceUnitData = class("ResourceUnitData", BaseData)
local StoreConst = require("const.StoreConst")

local schema = {}
schema["id"] = {"number", 0}
schema["num"] = {"number", 0}
schema["config"] = {"table", {}}
ResourceUnitData.schema = schema

function ResourceUnitData:ctor()
    ResourceUnitData.super.ctor(self)
end

function ResourceUnitData:update(data, isAdd)
    local num = self:getNum()
    self:setProperties(data)
    if isAdd then
        local newNum = num + data.num
        self:setNum(newNum)
    end
end

function ResourceUnitData:getPureParam()
    local param = {}
    param.id = self:getId()
    param.num = self:getNum()
    return param
end

function ResourceData:ctor()
    ResourceData.super.ctor(self)
    self._resList = {}
end

function ResourceData:init()
    self:_initData()
end

function ResourceData:_setUnitData(data, isAdd)
    local unit = self._resList["k_" .. data.id]
    if not unit then
        unit = ResourceUnitData.new()
        self._resList["k_" .. data.id] = unit
    end
    unit:update(data, isAdd)
end

function ResourceData:save()
    local result = {}
    for _, unit in pairs(self._resList) do
        local param = unit:getPureParam()
        table.insert(result, param)
    end
    G_StoreManager:setDataList(StoreConst.RESOURCE, result)
end

function ResourceData:_initData()
    local dataList = G_StoreManager:getDataList(StoreConst.RESOURCE)
    for i = 1, #dataList do
        self:_setUnitData(dataList[i])
    end
end

function ResourceData:getResUnitData(id)
    local unit = self._resList["k_" .. id]
    return unit
end

function ResourceData:addData(id, num, isAdd)
    local data = {}
    data.id = id
    data.num = num or 0
    self:_setUnitData(data, isAdd)
end

function ResourceData:getResNum(id)
    local resData = self:getResUnitData(id)
    if resData then
        return resData:getNum()
    end
    return 0
end

function ResourceData:useRes(id, num)
    local resData = self:getResUnitData(id)
    if resData then
        local curNum = resData:getNum()
        if curNum >= num then
            local newNum = curNum - num
            resData:setNum(newNum)
            G_SignalManager:dispatch(SignalConst.EVENT_RES_USE_SUCCES)
            return true
        end
    end
    return false
end

return ResourceData
